package com.cdy.demo.algorithm;

import java.io.IOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MonkeyTakeBanana {

    public static Integer bananas = 100;
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();
    private static final Condition condition2 = lock.newCondition();



    public static void main(String[] args) throws IOException {

//        Thread monkey1 = new Thread(() -> takeV2(2));
//        Thread monkey2 = new Thread(() -> takeV2(3));

        Thread monkey1 = new Thread(() -> take(2,condition,condition2));
        Thread monkey2 = new Thread(() -> take(3,condition2,condition));
        monkey1.start();
        monkey2.start();

        System.in.read();
        System.out.println(bananas);
        monkey1.interrupt();
        monkey2.interrupt();
    }

    public static void take(int num) {
       try {
           lock.lock();
           while (true) {
               if (bananas < num) {
                   return;
               }
               bananas -= num;
               System.out.println(Thread.currentThread().getName() + " take " + num);
               condition.signalAll();
               condition.await();
           }
       } catch (InterruptedException e) {
           e.printStackTrace();
       } finally {
           lock.unlock();
       }
    }

    public static void take(int num, Condition condition, Condition condition2) {
        try {
            lock.lock();
            while (true) {
                if (bananas < num) {
                    return;
                }
                bananas -= num;
                System.out.println(Thread.currentThread().getName() + " take " + num);
                condition2.signalAll();
                condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static  void takeV2(int num) {
        synchronized (condition) {
            try {
                while (true) {
                    if (bananas < num) {
                        return;
                    }
                    bananas -= num;
                    System.out.println(Thread.currentThread().getName() + " take " + num);
                    condition.notifyAll();
                    condition.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
